package com.gfxy.educational.service;

import com.gfxy.educational.entity.EduCourseTime;
import com.gfxy.educational.entity.EduJobTimeType;
import com.gfxy.educational.quartz.StudentAppraiseTask;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * @author: lijixin 2019-05-24
 */
@Service
public class QuartzService {

    private static final Logger logger = LoggerFactory.getLogger(QuartzService.class);

    public static final String SUMMER_PUSH_TRIGGER_NAME = "SUMMER_PUSH";
    public static final String WINTER_PUSH_TRIGGER_NAME = "WINTER_PUSH";
    public static final String COURSE_TIME_PARAM = "COURSE_TIME";

    @Autowired
    private JobTimeTypeService jobTimeTypeService;
    @Autowired
    private CourseTimeService courseTimeService;

    @Autowired
    private Scheduler scheduler;


    public boolean initPushJob()  {
        logger.info("开始初始化Quartz 推送任务");
        boolean result = false;

        try {
            EduJobTimeType jobTimeType = jobTimeTypeService.getCurrentTime();
            List<EduCourseTime> courseTimeList = courseTimeService.getAllCourseTimeService();

            JobDetail job = newJob(StudentAppraiseTask.class)
                    .withIdentity("studentAppraiseTask","studentAppraiseTask")
                    .storeDurably()
                    .build();
            scheduler.addJob(job,true);

            for(EduCourseTime courseTime : courseTimeList){

                TriggerBuilder triggerBuilder = newTrigger()
                        .forJob(job);
                String triggerName = "";
                String triggerGroup = "";
                if(courseTime.getJobTimeTypeId().equals("0")){
                    // 夏季时间
                    triggerName = SUMMER_PUSH_TRIGGER_NAME+"_"+courseTime.getArrangementId();
                    triggerGroup = SUMMER_PUSH_TRIGGER_NAME;

                } else {
                    //冬季时间
                    triggerName = WINTER_PUSH_TRIGGER_NAME+"_"+courseTime.getArrangementId();
                    triggerGroup = WINTER_PUSH_TRIGGER_NAME;
                }
                triggerBuilder.withIdentity(triggerName,triggerGroup);
                triggerBuilder.withSchedule(this.getCronSchedule(courseTime.getEndTime()));
                Trigger trigger = triggerBuilder.build();
                trigger.getJobDataMap().put(COURSE_TIME_PARAM,courseTime);
                try {
                    scheduler.scheduleJob(trigger);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }


                if(!courseTime.getJobTimeTypeId().equals(jobTimeType.getId())){
                    //正在执行
                    scheduler.pauseTrigger(TriggerKey.triggerKey(triggerName));
                }
            }
            result = true;
        } catch (SchedulerException e) {
            logger.error("初始化推送定时任务出错：",e);
            result = false;
        }

        return result;

    }

    private ScheduleBuilder getCronSchedule(String endTime) {
        String[] times = endTime.split(":");
        String cronStr = times[2] + " " + times[1] + " " + times[0] + " * * ?";
        System.out.println(cronStr);
//        String cornStr = "0 * * * * ? "
        return cronSchedule(cronStr);
    }

    /**
     * 启动触发器
     * @param jobTimeTypeId 0-夏季时间 1-冬季时间
     */
    public void startTrigger(String jobTimeTypeId) throws SchedulerException {
        if(jobTimeTypeId.equals("0")){
            scheduler.resumeTriggers(GroupMatcher.groupStartsWith(SUMMER_PUSH_TRIGGER_NAME));
        } else {
            scheduler.resumeTriggers(GroupMatcher.groupStartsWith(WINTER_PUSH_TRIGGER_NAME));
        }
    }

    /**
     * 暂停触发器
     * @param jobTimeTypeId 0-夏季时间 1-冬季时间
     */
    public void pauseTrigger(String jobTimeTypeId) throws SchedulerException {
        if(jobTimeTypeId.equals("0")){
            scheduler.pauseTriggers(GroupMatcher.groupStartsWith(SUMMER_PUSH_TRIGGER_NAME));
        } else {
            scheduler.pauseTriggers(GroupMatcher.groupStartsWith(WINTER_PUSH_TRIGGER_NAME));
        }

    }
}
